import { Context, Next } from 'koa';

export const errorHandler = async (ctx: Context, next: Next) => {
  try {
    await next();
  } catch (err: any) {
    // 设置状态码
    ctx.status = err.status || 500;
    
    // 错误响应
    ctx.body = {
      error: true,
      status: ctx.status,
      message: err.message || 'Internal Server Error',
      timestamp: new Date().toISOString()
    };

    // 输出错误日志
    console.error('Error occurred:', {
      status: ctx.status,
      message: err.message,
      stack: err.stack,
      url: ctx.url,
      method: ctx.method,
    });

    // 向上抛出错误，让Koa处理
    ctx.app.emit('error', err, ctx);
  }
}; 